package com.itheima.serviceimpl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.itheima.dao.MenuDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.JedisPool;

import java.util.*;

@Service(interfaceClass = MenuService.class)
@Transactional
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuDao menuDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private JedisPool jedisPool;

    @Override
    public List<Menu> findAll(String username) {

        //根据username查询用户
        User user = userDao.FindUserByName(username);
        //根据userId查询对应的角色
        Set<Role> roles = roleDao.findByUserId(user.getId());
        //创建一个set集合存储父菜单
        List<Menu> menuFathers = new ArrayList<>();
        Menu menu = null;
        Set<Integer> menuIds = new HashSet<>();
        //循环遍历获取菜单id
        for (Role role : roles) {
            List<Integer> menuid = menuDao.findMenuIdByRoleId(role.getId());
            for (Integer integer : menuid) {
                menuIds.add(integer);
            }
        }
        //根据菜单id查询所有的父级菜单
        for (Integer menuId : menuIds) {
            Menu menuFather = menuDao.findMenuByFather(menuId);
            if (menuFather != null) {
                //说明是父级菜单,根据父级菜单的id查询子菜单
                List<Menu> menuList = menuDao.findMenuByFatherId(menuFather.getId());
                //将子菜单赋值给父级菜单
                menuFather.setChildren(menuList);
                menuFathers.add(menuFather);
            }
        }
        String json = JSON.toJSON(menuFathers).toString();
        jedisPool.getResource().setex(username, 60 * 60 * 24 * 30,json);
        return menuFathers;
    }


    @Override
    public List<Menu> findAllMenu() {
        return menuDao.findAllMenu();
    }
}
